import { defineStore } from 'pinia';
import http from '@/http';
import cache from '@/utils/cache';

interface loginData {
    username?:string,
    password?:string
}

interface registerData {
    email:string,
    registerPassword:string,
    nickname:string,
    sex:string
}

export const useUsersStore = defineStore('user', {
    state: () => 
    {
        return {
            userData:{} as any,
            AMapData:null as any, // 当前定位信息
            themeValue:false
        };
    },
    getters: {
        getUserName: (state) =>
        {
            return state.userData.username || JSON.parse(cache.userData.get()).username;
        },
        get_Id: (state) =>
        {
            return state.userData.id || JSON.parse(cache.userData.get()).id;
        },
        getUserData: (state) => 
        {
            return state.userData || JSON.parse(cache.userData.get());
        }
    },
    actions: {
        setData (data:any)
        {
            // 缓存本地和store
            this.userData = data;
            cache.userData.set(JSON.stringify(data));
        },
        async login (data:loginData)
        {
            const res = await http.user.login(data);
            return res;
        },
        async register (data:registerData)
        {
            const res = await http.user.register(data);
            return res;
        },
        async checkUserState ()
        {
            const res = await http.user.checkUserState();
            this.setData(res.data.content);
            return res;
        },
        clearCacheUserData ()
        {
            cache.userData.remove();
            cache.token.remove();
            cache.backupId.remove();
        },
        loginOut ()
        {
            this.clearCacheUserData();
            window.location.reload();
        }
    }
});